﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Admin_Evaluations : System.Web.UI.Page
{
    protected int CourseID
    {
        get
        {
            return (int)ViewState["CourseID"];
        }
        set
        {
            ViewState["CourseID"] = value;
        }
    }

    protected string EvaluationIntroduction
    {
        get
        {
            return (string)ViewState["EvaluationIntroduction"];
        }
        set
        {
            ViewState["EvaluationIntroduction"] = value;
        }
    }

    protected string strEvaluationQuestions
    {
        get
        {
            return Session["xDocEvaluationQuestions"].ToString();
        }
        set
        {
            Session["xDocEvaluationQuestions"] = value;
        }
    }

    ILE_Global ileGlobal = new ILE_Global();

    EvaluationsBLL evaluationsLogic = new EvaluationsBLL();

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    #region Create Evaluation

    protected void btnCreateEvaluation_Click(object sender, EventArgs e)
    {
        PanelCreateEvaluation.Visible = true;
        PanelEditEvaluation.Visible = false;
        PanelViewEvaluations.Visible = false;
        WizardCreateEvaluation.ActiveStepIndex = 0;
    }

    protected void GridViewCourses_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (GridViewCourses.SelectedIndex != -1)
        {
            CourseID = Convert.ToInt32(((GridView)sender).SelectedValue.ToString());
            LoadSectionsByCourseID(false);
            WizardCreateEvaluation.NavigationStyle.CssClass = "";
        }
        else
        {
            PanelCreateEvaluationSections.Visible = false;
            WizardCreateEvaluation.NavigationStyle.CssClass = "Hidden";
        }
    }

    protected void chkboxCreateEvaluationSectionsShowDisabled_CheckedChanged(object sender, EventArgs e)
    {
        LoadSectionsByCourseID(((CheckBox)sender).Checked);
    }

    protected void LoadSectionsByCourseID(bool showDisabled)
    {
        ClassBLL classLogic = new ClassBLL();

        lstboxSections.Items.Clear();

        Classes.Courses_SectionDataTable sections = classLogic.GetSectionsByCourseID(CourseID, false);

        foreach (Classes.Courses_SectionRow section in sections)
        {
            ListItem newItem = new ListItem(section.SectionNumber.ToString(), section.SectionNumber.ToString());
            if (showDisabled)
            {
                lstboxSections.Items.Add(newItem);
            }
            else
            {
                if (section.IsEnabled == true)
                    lstboxSections.Items.Add(newItem);
            }
        }

        PanelCreateEvaluationSections.Visible = true;
    }

    protected void WizardCreateEvaluation_ActiveStepChanged(object sender, EventArgs e)
    {
        if (WizardCreateEvaluation.ActiveStepIndex == 1)
        {
            if (GridViewCourses.SelectedIndex == -1)
            {
                WizardCreateEvaluation.ActiveStepIndex = 0;
                // *SteveMsg
                string _msg = "You must select a class to assign the quiz to.";
                ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
                return;
            }

            if (lstboxSections.SelectedIndex == -1)
            {
                WizardCreateEvaluation.ActiveStepIndex = 0;
                // *SteveMsg
                string _msg = "At least 1 section must be selected from the 'Sections' Listbox.";
                ModalPopupMessage.ShowModalPopup("ILE Message", _msg, 2);
            }
            else
            {
                XDocument xDocEvaluationQuestions = new XDocument();
                xDocEvaluationQuestions.Declaration = new XDeclaration("1.0", "utf-8", "yes");
                if (xDocEvaluationQuestions.ToString() == String.Empty)
                {
                    xDocEvaluationQuestions.Document.Add(new XElement("evaluationquestions", new XElement("questions")));
                }
                strEvaluationQuestions = xDocEvaluationQuestions.ToString();
                Fill_ddlistCreateQuestionList();

            }
        }
        else if (WizardCreateEvaluation.ActiveStepIndex == 2)
        {
            EvaluationIntroduction = EditorCreateIntroduction.Content;
        }
    }

    private void Fill_ddlistCreateQuestionList()
    {
        XDocument xDocEvaluationQuestions = XDocument.Parse(strEvaluationQuestions);
        List<XElement> _questions = xDocEvaluationQuestions.Descendants("question").ToList();

        ddlistCreateQuestionList.Items.Clear();

        if (_questions.Count == 0)
        {
            ListItem newItem = new ListItem("Add : A Question");
            ddlistCreateQuestionList.Items.Add(newItem);
        }
        else
        {
            ddlistCreateQuestionList.Items.Add(new ListItem("Add : A Question"));
            foreach (XElement question in _questions)
            {
                string questiontext = question.Element("questiontext").Value.ToString();
                questiontext = System.Text.RegularExpressions.Regex.Replace(questiontext, "<br />", " ");
                questiontext = System.Text.RegularExpressions.Regex.Replace(questiontext, "<[^>]*>", String.Empty);
                if (questiontext.Length > 60)
                {
                    questiontext = questiontext.Substring(0, 60);
                    questiontext = questiontext + "...";
                }
                ListItem newItem = new ListItem("Edit : " + question.Attribute("id").Value.ToString() + " - " + questiontext, question.Attribute("id").Value.ToString());
                ddlistCreateQuestionList.Items.Add(newItem);
            }
        }
    }

    protected void ddlistCreateQuestionList_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList ddlist = (DropDownList)sender;

        if (ddlist.SelectedIndex == 0)
        {
            lblCreateMode.Text = "Add New Questions";
            btnCreateAddNewQuestion.Visible = true;
            btnCreateUpdateQuestion.Visible = false;
            EditorCreateQuestion.Content = String.Empty;
        }
        else
        {
            lblCreateMode.Text = "Edit Questions";
            int QuestionID = Convert.ToInt32(ddlist.SelectedValue);
            LoadQuestionToEdit(QuestionID);
            btnCreateAddNewQuestion.Visible = false;
            btnCreateUpdateQuestion.Visible = true;
        }
    }

    protected void btnCreateUpdateQuestion_Click(object sender, EventArgs e)
    {
        XDocument xDocEvaluationQuestions = XDocument.Parse(strEvaluationQuestions);

        int QuestionID = Convert.ToInt32(ddlistCreateQuestionList.SelectedValue);
        string questiontext = EditorCreateQuestion.Content.ToString();
        string questiontype = ddlistCreateQuestionType.SelectedValue.ToString();

        XElement element = xDocEvaluationQuestions.Descendants("question").Where(el => el.Attribute("id").Value.ToString() == QuestionID.ToString()).First();
        element.ReplaceAttributes(new XAttribute("id", element.Attribute("id").Value.ToString()), new XAttribute("type", questiontype));
        element.ReplaceNodes(new XElement("questiontext", questiontext));

        Fill_ddlistCreateQuestionList();

        EditorCreateQuestion.Content = String.Empty;
        btnCreateAddNewQuestion.Visible = true;
        btnCreateUpdateQuestion.Visible = false;

        ModalPopupMessage.ShowModalPopup("ILE Message", "Question Successfully Updated.", 1);

        strEvaluationQuestions = xDocEvaluationQuestions.ToString();
    }

    private void LoadQuestionToEdit(int QuestionID)
    {
        XDocument xDocEvaluationQuestions = XDocument.Parse(strEvaluationQuestions);

        XElement question = xDocEvaluationQuestions.Descendants("question").Where(el => el.Attribute("id").Value.ToString() == QuestionID.ToString()).First();

        if (question.Attribute("type").Value == "scale10")
        {
            ddlistCreateQuestionType.SelectedIndex = 0;
        }
        else
        {
            ddlistCreateQuestionType.SelectedIndex = 1;
        }

        EditorCreateQuestion.Content = question.Element("questiontext").Value.ToString();
    }

    protected void ddlistCreateQuestionType_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList ddlist = (DropDownList)sender;
        switch (ddlist.SelectedValue)
        {
            case "scale10":
                PanelCreateScale10.Visible = true;
                PanelCreateShortAnswer.Visible = false;
                break;
            case "shortanswer":
                PanelCreateScale10.Visible = false;
                PanelCreateShortAnswer.Visible = true;
                break;
        }
    }

    protected void btnCreateAddNewQuestion_Click(object sender, EventArgs e)
    {
        XDocument xDocEvaluationQuestions = XDocument.Parse(strEvaluationQuestions);

        string questiontext = EditorCreateQuestion.Content.ToString();
        string type = ddlistCreateQuestionType.SelectedValue;

        int QuestionID = 1;

        if (xDocEvaluationQuestions.Descendants("question").Count() != 0)
            QuestionID = Convert.ToInt32(xDocEvaluationQuestions.Descendants("question").Last().Attribute("id").Value) + 1;

        xDocEvaluationQuestions.Element("evaluationquestions").Element("questions").Add(
            new XElement("question", new XAttribute("id", QuestionID.ToString()), new XAttribute("type", type),
                    new XElement("questiontext", questiontext)));

        strEvaluationQuestions = xDocEvaluationQuestions.ToString();
        Fill_ddlistCreateQuestionList();

        ddlistCreateQuestionType.SelectedIndex = 0;
        EditorCreateQuestion.Content = String.Empty;

        ModalPopupMessage.ShowModalPopup("ILE Message", "Question Successfully Added.", 1);
    }

    protected void WizardCreateEvaluation_FinishButtonClick(object sender, EventArgs e)
    {
        XDocument xDocEvaluationQuestions = XDocument.Parse(strEvaluationQuestions);

        if (xDocEvaluationQuestions.Descendants("question").Count() == 0)
        {
            ModalPopupMessage.ShowModalPopup("ILE Message", "Need at least one question to create evaluation.", 2);
            return;
        }

        int EvaluationID = evaluationsLogic.InsertEvaluation(EvaluationIntroduction, xDocEvaluationQuestions.ToString());

        if (EvaluationID != 0)
        {
            bool result = false;
            bool isDuplicated = false;
            foreach (ListItem item in lstboxSections.Items)
            {
                if (item.Selected)
                {
                    isDuplicated = evaluationsLogic.RelationsIsDuplicated(CourseID, Convert.ToInt32(item.Value));
                    if (isDuplicated == true)
                        break;
                }
            }
            if (!isDuplicated)
            {
                foreach (ListItem item in lstboxSections.Items)
                {
                    if (item.Selected)
                    {
                        result = evaluationsLogic.InsertRelation(EvaluationID, CourseID, Convert.ToInt32(item.Value));
                        if (result == false)
                            break;
                    }
                }

                if (result == true)
                {
                    ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", "Evaluation Successfully Created.", 1, "Evaluations.aspx");
                }
                else
                {
                    ModalPopupMessage.ShowModalPopup("ILE Message", "Failed to Create Evaluation.", 2);
                    ileGlobal.RecordError("Admin/Evaluations.aspx.cs:WizardCreateEvaluation_FinishButtonClick:000", "Failed to insert relation for evaluation. Evaluation with ID " + EvaluationID.ToString() + " needs to be deleted", 4, Request.Browser);
                }
            }
            else
            {
                ModalPopupMessage.ShowModalPopup("ILE Message", "Failed to Create Evaluation. An evaluation is already assigned to the section.", 2);
            }
        }
        else
        {
            ModalPopupMessage.ShowModalPopup("ILE Message", "Failed to Create Evaluation.", 2);
            ileGlobal.RecordError("Admin/Evaluations.aspx.cs:WizardCreateEvaluation_FinishButtonClick:001", "Could not Insert Evaluation", 3, Request.Browser);
        }
    }

    #endregion

    #region Edit Evaluation
    protected void btnEditEvaluation_Click(object sender, EventArgs e)
    {
        PanelCreateEvaluation.Visible = false;
        PanelEditEvaluation.Visible = true;
        PanelViewEvaluations.Visible = false;
        WizardEditEvaluation.ActiveStepIndex = 0;
        EvaluationIntroduction = String.Empty;
    }

    protected void ddlistEditCourses_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            DropDownList Sender = (DropDownList)sender;
            ClassBLL classLogic = new ClassBLL();
            Classes.CoursesDataTable courses = classLogic.GetCoursesOrderByTitle();

            Sender.Items.Clear();

            ListItem newItem = new ListItem("--- Select a Course ---", "0");

            Sender.Items.Add(newItem);

            foreach (Classes.CoursesRow course in courses)
            {
                ListItem item = new ListItem();
                item.Text = course.Title;
                item.Value = course.CourseID.ToString();

                Sender.Items.Add(item);
            }
        }
    }

    protected void GridViewEvalClasses_SelectedIndexChanged(object sender, EventArgs e)
    {
        GridView Sender = (GridView)sender;
        if (Sender.SelectedIndex != -1)
        {
            WizardEditEvaluation.NavigationStyle.CssClass = "";
        }
        else
        {
            WizardEditEvaluation.NavigationStyle.CssClass = "Hidden";
        }
    }

    //protected void ddlistEditCourses_SelectedIndexChanged(object sender, EventArgs e)
    //{
    //    DropDownList Sender = (DropDownList)sender;

    //    int CourseID = Convert.ToInt32(Sender.SelectedValue);

    //    ClassBLL classLogic = new ClassBLL();
    //    Classes.Courses_SectionDataTable sections = classLogic.GetSectionsByCourseID(CourseID, false);

    //    ddlistEditSections.Items.Clear();

    //    ListItem newItem = new ListItem("--- Select a Section ---", "0");

    //    ddlistEditSections.Items.Add(newItem);

    //    foreach (Classes.Courses_SectionRow section in sections)
    //    {
    //        ListItem item = new ListItem();
    //        item.Text = section.SectionNumber.ToString();
    //        item.Value = section.SectionNumber.ToString();

    //        ddlistEditSections.Items.Add(item);
    //    }
    //}

    protected void ddlistEditSections_Load(object sender, EventArgs e)
    {
        //DropDownList Sender = (DropDownList)sender;
        //Sender.Items.Clear();
        //ListItem item = new ListItem("--- Please Select a Course ---", "0");
        //Sender.Items.Add(item);
    }

    //protected void ddlistEditSections_SelectedIndexChanged(object sender, EventArgs e)
    //{
    //    DropDownList Sender = (DropDownList)sender;
    //    if (Sender.SelectedIndex != 0)
    //    {
    //        WizardEditEvaluation.NavigationStyle.CssClass = "";
    //    }
    //}

    protected void WizardEditEvaluation_ActiveStepChanged(object sender, EventArgs e)
    {
        Wizard Sender = (Wizard)sender;

        if (Sender.ActiveStepIndex == 0)
        {
            WizardEditEvaluation.NavigationStyle.CssClass = "Hidden";
            
            GridViewEvalClasses.SelectedIndex = -1;
        }
        else if (Sender.ActiveStepIndex == 1)
        {
            int CourseID = Convert.ToInt32(GridViewEvalClasses.SelectedDataKey["CourseID"].ToString());
            int SectionNumber = Convert.ToInt32(GridViewEvalClasses.SelectedDataKey["SectionNumber"].ToString());
            Evaluations._Relations_Evaluations_Courses_SectionDataTable relations =
                evaluationsLogic.GetRelationsByCourseIdAndSectionNumber(CourseID, SectionNumber);

            try
            {
                int EvaluationID = relations[0].EvaluationID;
                Evaluations.EvaluationsRow evaluation = evaluationsLogic.GetEvaluation(EvaluationID);
                if(EvaluationIntroduction == String.Empty)
                    EvaluationIntroduction = evaluation.Introduction;
                EditorEditIntroduction.Content = EvaluationIntroduction;
                XDocument xDocEvaluationQuestions = XDocument.Parse(evaluation.Questions);
                strEvaluationQuestions = xDocEvaluationQuestions.ToString();
            }
            catch
            {
                ModalPopupMessage.ShowModalPopup("ILE Message", "This class does not have an evaluation assigned.", 2);
                Sender.ActiveStepIndex = 0;
            }
        }
        else if (Sender.ActiveStepIndex == 2)
        {
            EvaluationIntroduction = EditorEditIntroduction.Content;
            Fill_ddlistEditQuestionList();
        }
    }

    private void Fill_ddlistEditQuestionList()
    {
        XDocument xDocEvaluationQuestions = XDocument.Parse(strEvaluationQuestions);
        List<XElement> _questions = xDocEvaluationQuestions.Descendants("question").ToList();

        ddlistEditQuestionList.Items.Clear();

        if (_questions.Count == 0)
        {
            ListItem newItem = new ListItem("Add : A Question");
            ddlistEditQuestionList.Items.Add(newItem);
        }
        else
        {
            ddlistEditQuestionList.Items.Add(new ListItem("Add : A Question"));
            foreach (XElement question in _questions)
            {
                string questiontext = question.Element("questiontext").Value.ToString();
                questiontext = System.Text.RegularExpressions.Regex.Replace(questiontext, "<br />", " ");
                questiontext = System.Text.RegularExpressions.Regex.Replace(questiontext, "<[^>]*>", String.Empty);
                if (questiontext.Length > 60)
                {
                    questiontext = questiontext.Substring(0, 60);
                    questiontext = questiontext + "...";
                }
                ListItem newItem = new ListItem("Edit : " + question.Attribute("id").Value.ToString() + " - " + questiontext, question.Attribute("id").Value.ToString());
                ddlistEditQuestionList.Items.Add(newItem);
            }
        }
    }

    protected void ddlistEditQuestionList_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList ddlist = (DropDownList)sender;

        if (ddlist.SelectedIndex == 0)
        {
            lblEditMode.Text = "Add New Questions";
            btnEditAddNewQuestion.Visible = true;
            btnEditUpdateQuestion.Visible = false;
            EditorEditQuestion.Content = String.Empty;
        }
        else
        {
            lblEditMode.Text = "Edit Questions";
            int QuestionID = Convert.ToInt32(ddlist.SelectedValue);
            LoadEditQuestionToEdit(QuestionID);
            btnEditAddNewQuestion.Visible = false;
            btnEditUpdateQuestion.Visible = true;
        }
    }

    protected void btnEditUpdateQuestion_Click(object sender, EventArgs e)
    {
        XDocument xDocEvaluationQuestions = XDocument.Parse(strEvaluationQuestions);

        int QuestionID = Convert.ToInt32(ddlistEditQuestionList.SelectedValue);
        string questiontext = EditorEditQuestion.Content.ToString();
        string questiontype = ddlistEditQuestionType.SelectedValue.ToString();

        XElement element = xDocEvaluationQuestions.Descendants("question").Where(el => el.Attribute("id").Value.ToString() == QuestionID.ToString()).First();
        element.ReplaceAttributes(new XAttribute("id", element.Attribute("id").Value.ToString()), new XAttribute("type", questiontype));
        element.ReplaceNodes(new XElement("questiontext", questiontext));

        strEvaluationQuestions = xDocEvaluationQuestions.ToString();

        Fill_ddlistEditQuestionList();

        EditorEditQuestion.Content = String.Empty;
        btnEditAddNewQuestion.Visible = true;
        btnEditUpdateQuestion.Visible = false;

        ModalPopupMessage.ShowModalPopup("ILE Message", "Question Successfully Updated.", 1);
    }

    private void LoadEditQuestionToEdit(int QuestionID)
    {
        XDocument xDocEvaluationQuestions = XDocument.Parse(strEvaluationQuestions);

        XElement question = xDocEvaluationQuestions.Descendants("question").Where(el => el.Attribute("id").Value.ToString() == QuestionID.ToString()).First();

        if (question.Attribute("type").Value == "scale10")
        {
            ddlistEditQuestionType.SelectedIndex = 0;
        }
        else
        {
            ddlistEditQuestionType.SelectedIndex = 1;
        }

        EditorEditQuestion.Content = question.Element("questiontext").Value.ToString();
    }

    protected void ddlistEditQuestionType_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList ddlist = (DropDownList)sender;
        switch (ddlist.SelectedValue)
        {
            case "scale10":
                PanelEditScale10.Visible = true;
                PanelEditShortAnswer.Visible = false;
                break;
            case "shortanswer":
                PanelEditScale10.Visible = false;
                PanelEditShortAnswer.Visible = true;
                break;
        }
    }

    protected void btnEditAddNewQuestion_Click(object sender, EventArgs e)
    {
        string questiontext = EditorEditQuestion.Content.ToString();
        string type = ddlistEditQuestionType.SelectedValue;

        int QuestionID = 1;

        XDocument xDocEvaluationQuestions = XDocument.Parse(strEvaluationQuestions);

        if (xDocEvaluationQuestions.Descendants("question").Count() != 0)
            QuestionID = Convert.ToInt32(xDocEvaluationQuestions.Descendants("question").Last().Attribute("id").Value) + 1;

        xDocEvaluationQuestions.Element("evaluationquestions").Element("questions").Add(
            new XElement("question", new XAttribute("id", QuestionID.ToString()), new XAttribute("type", type),
                    new XElement("questiontext", questiontext)));

        strEvaluationQuestions = xDocEvaluationQuestions.ToString();

        Fill_ddlistEditQuestionList();

        ddlistEditQuestionType.SelectedIndex = 0;
        EditorEditQuestion.Content = String.Empty;

        ModalPopupMessage.ShowModalPopup("ILE Message", "Question Successfully Added.", 1);
    }

    protected void WizardEditEvaluation_FinishButtonClick(object sender, EventArgs e)
    {
        XDocument xDocEvaluationQuestions = XDocument.Parse(strEvaluationQuestions);

        if (xDocEvaluationQuestions.Descendants("question").Count() == 0)
        {
            ModalPopupMessage.ShowModalPopup("ILE Message", "Need at least one question to create evaluation.", 2);
            return;
        }

        int CourseID = Convert.ToInt32(GridViewEvalClasses.SelectedDataKey["CourseID"].ToString());
        int SectionNumber = Convert.ToInt32(GridViewEvalClasses.SelectedDataKey["SectionNumber"].ToString());
        Evaluations._Relations_Evaluations_Courses_SectionDataTable relations =
            evaluationsLogic.GetRelationsByCourseIdAndSectionNumber(CourseID, SectionNumber);

        int EvaluationID = 0;

        try
        {
            EvaluationID = relations[0].EvaluationID;
        }
        catch
        {
            ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", "Could not laod EvaluationID.", 2, "Evaluations.aspx");
        }

        bool result = evaluationsLogic.UpdateEvaluation(EvaluationIntroduction, xDocEvaluationQuestions.ToString(), EvaluationID);

        if (result)
        {
            ModalPopupMessage.ShowModalPopup_Redirect("ILE Message", "Evaluation Updated Successfully.", 1, "Evaluations.aspx");
        }
        else
        {
            ModalPopupMessage.ShowModalPopup("ILE Message", "Failed to Update the Evaluation.", 2);
        }
    }

    #endregion


    protected void btnViewEvaluations_Click(object sender, EventArgs e)
    {
        PanelCreateEvaluation.Visible = false;
        PanelEditEvaluation.Visible = false;
        PanelViewEvaluations.Visible = true;
    }

    protected void ddlistViewCourses_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            DropDownList Sender = (DropDownList)sender;
            ClassBLL classLogic = new ClassBLL();
            Classes.CoursesDataTable courses = classLogic.GetCourses();

            Sender.Items.Clear();

            ListItem newItem = new ListItem("--- Select a Course ---", "0");

            Sender.Items.Add(newItem);

            foreach (Classes.CoursesRow course in courses)
            {
                ListItem item = new ListItem();
                item.Text = course.Title;
                item.Value = course.CourseID.ToString();

                Sender.Items.Add(item);
            }
        }
    }

    protected void ddlistViewCourses_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList Sender = (DropDownList)sender;

        int CourseID = Convert.ToInt32(Sender.SelectedValue);

        ClassBLL classLogic = new ClassBLL();
        Classes.Courses_SectionDataTable sections = classLogic.GetSectionsByCourseID(CourseID, false);

        ddlistViewSections.Items.Clear();

        ListItem newItem = new ListItem("--- Select a Section ---", "0");

        ddlistViewSections.Items.Add(newItem);

        foreach (Classes.Courses_SectionRow section in sections)
        {
            ListItem item = new ListItem();
            item.Text = section.SectionNumber.ToString();
            item.Value = section.SectionNumber.ToString();

            ddlistViewSections.Items.Add(item);
        }
    }

    protected void ddlistViewSections_Load(object sender, EventArgs e)
    {
    }

    protected void ddlistViewSections_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList Sender = (DropDownList)sender;
        if (Sender.SelectedIndex != 0)
        {
            LoadViewEvaluationSubmissions();
        }
    }

    protected int SubmissionCounter
    {
        get
        {
            return (int)ViewState["SubmissionCounter"];
        }
        set
        {
            ViewState["SubmissionCounter"] = value;
        }
    }

    private void LoadViewEvaluationSubmissions()
    {
        int CourseID = Convert.ToInt32(ddlistViewCourses.SelectedValue);
        int SectionNumber = Convert.ToInt32(ddlistViewSections.SelectedValue);

        Evaluations.Evaluations_SubmissionsDataTable submissions = evaluationsLogic.GetEvaluationSubmissionsByCourseIdAndSectionNumber(CourseID, SectionNumber);

        if (submissions.Count == 0)
        {
            ModalPopupMessage.ShowModalPopup("ILE Message", "No Submissions", 2);
            return;
        }
        else if (submissions.Count >= 1)
        {
            HttpContext.Current.Session["ViewUserID"] = submissions[0].UserID;

            SubmissionCounter = 1;

            RepeaterViewSubmissionList.DataSource = submissions.Rows;
            RepeaterViewSubmissionList.DataBind();

            Evaluations.EvaluationsRow evaluation = evaluationsLogic.GetEvaluation(submissions[0].EvaluationID);
            lblViewEvaluationIntroduction.Text = evaluation.Introduction.ToString();

            LoadViewEvaluationSubmission(CourseID, SectionNumber, submissions[0].UserID);

            PanelViewEvaluationResults.Visible = true;
        }
    }

    private void LoadViewEvaluationSubmission(int CourseID, int SectionNumber, int UserID)
    {
        // Update User Info
        ObjectDataSourceViewUser.DataBind();
        DetailsViewUser.DataBind();

        // Question...
        Evaluations.Evaluations_SubmissionsRow submission = 
            evaluationsLogic.GetEvaluationSubmissionsByCourseIdAndSectionNumberAndUserId(CourseID, SectionNumber, UserID);

        XDocument xDocEvaluationAnswers = new XDocument();
        xDocEvaluationAnswers = XDocument.Parse(submission.Answers.ToString());

        lblViewEvaluationQuestions.Text = "";

        List<XElement> questions = xDocEvaluationAnswers.Descendants("question").ToList();

        lblViewEvaluationQuestions.Text = String.Empty;

        int counter = 1;
        foreach (XElement question in questions)
        {
            lblViewEvaluationQuestions.Text += counter.ToString() + ". " + question.Element("questiontext").Value.ToString() + "<br />";
            if (question.Attribute("type").Value.ToString() == "scale10")
            {
                lblViewEvaluationQuestions.Text += "<table style='margin-left: 20px;'><tr>";
                for (int i = 1; i <= 10; i++)
                {
                    if (question.Element("answer").Value.ToString() == i.ToString())
                    {
                        lblViewEvaluationQuestions.Text += "<td style='text-align: center;'><input type='radio' name='" + question.Attribute("id").Value.ToString() + "' value='" + i.ToString() + "' checked /></td>";
                    }
                    else
                    {
                        lblViewEvaluationQuestions.Text += "<td style='text-align: center;'><input type='radio' name='" + question.Attribute("id").Value.ToString() + "' value='" + i.ToString() + "' /></td>";
                    }
                    
                }
                lblViewEvaluationQuestions.Text += "</tr><tr>";
                for (int i = 1; i <= 10; i++)
                {
                    if (i == 1)
                    {
                        lblViewEvaluationQuestions.Text += "<td style='text-align: center; vertical-align: top;'>" + i.ToString() + "<br />Strongly<br />Disagree</td>";
                    }
                    else if (i == 10)
                    {
                        lblViewEvaluationQuestions.Text += "<td style='text-align: center; vertical-align: top;'>" + i.ToString() + "<br />Strongly<br />Agree</td>";
                    }
                    else
                    {
                        lblViewEvaluationQuestions.Text += "<td style='text-align: center; vertical-align: top;'>" + i.ToString() + "</td>";
                    }
                }
                lblViewEvaluationQuestions.Text += "</tr></table><br /><br />";
            }
            else
            {
                lblViewEvaluationQuestions.Text += "<textarea name='" + question.Attribute("id").Value.ToString() + "' rows='3' cols='50'>" + question.Element("answer").Value.ToString() + "</textarea><br /><br />";
            }
            counter++;
        }
    }
    
    protected void RepeaterViewSubmissionList_Load(object sender, EventArgs e)
    {

    }

    
    protected void RepeaterViewSubmissionList_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Evaluations.Evaluations_SubmissionsRow row = e.Item.DataItem as Evaluations.Evaluations_SubmissionsRow;

            LinkButton lnkbtnSubmission = e.Item.FindControl("lnkbtnSubmission") as LinkButton;

            if (row.UserID.ToString() == HttpContext.Current.Session["ViewUserID"].ToString())
            {
                lnkbtnSubmission.ForeColor = System.Drawing.Color.Red;
                lnkbtnSubmission.Enabled = false;
            }
            else
            {
                //lnkbtnSubmission.ForeColor = null;
                lnkbtnSubmission.Font.Bold = true;
                lnkbtnSubmission.Enabled = true;
                lnkbtnSubmission.CommandArgument = row.UserID.ToString();
            }

            lnkbtnSubmission.Text = SubmissionCounter.ToString();
            SubmissionCounter++;
        }
    }

    protected void lnkbtnSubmission_Click(object sender, CommandEventArgs e)
    {
        int CourseID = Convert.ToInt32(ddlistViewCourses.SelectedValue);
        int SectionNumber = Convert.ToInt32(ddlistViewSections.SelectedValue);
        int UserID = Convert.ToInt32(e.CommandArgument);

        HttpContext.Current.Session["ViewUserID"] = UserID;

        LoadViewEvaluationSubmission(CourseID, SectionNumber, UserID);

        RepeaterViewSubmissionList.DataBind();
    }
    
}
